<template>
  <div class="coupon-box">
    <div class="title-box">
      <span>卡券类订单列表</span>
    </div>
    <div class="search-box">
      <div>
        <span>订单ID：</span>
        <el-input v-model="searchForm.sysOrderId" clearable placeholder="请输入订单ID" />
      </div>
      <div>
        <span>用户名称：</span>
        <el-input v-model="searchForm.buyUserName" clearable placeholder="请输入用户名称" />
      </div>
      <div>
        <span>商户：</span>
        <el-select style="width:100%;" v-model="searchForm.shopId" clearable filterable>
          <el-option v-for="item in shopOptions" :key="item.shopId" :label="item.shopName" :value="item.shopId" />
        </el-select>
      </div>
      <div>
        <span>订单状态：</span>
        <el-select style="width:100%;" v-model="searchForm.orderStatus" clearable>
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
    </div>
    <div class="search-box">
      <div>
        <span>商品：</span>
        <el-select style="width:100%;" v-model="searchForm.goodsId" clearable filterable>
          <el-option v-for="item in goodsOptions" :key="item.goodsId" :label="item.goodsName" :value="item.goodsId" />
        </el-select>
      </div>
      <div>
        <span>上游平台：</span>
        <el-select style="width:100%;" v-model="searchForm.channelCode" clearable filterable>
          <el-option v-for="item in channelOptions" :key="item.channelCode" :label="item.channelName" :value="item.channelCode" />
        </el-select>
      </div>
      <div style="width:30%;">
        <span>下单时间：</span>
        <el-date-picker v-model="searchForm.date" type="datetimerange" range-separator="至" start-placeholder="开始时间"
          end-placeholder="结束时间" />
      </div>
      <el-button style="margin-left:0;" type="primary" @click="searchHandle">查询</el-button>
      <el-button style="margin-left:0;" @click="resetHandle">重置</el-button>
      <el-button style="margin-left:auto;" @click="exportHandle(1)">全部导出</el-button>
    </div>
    <div class="table-box">
      <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
        :cell-style="{fontSize:'14px',color:'#7b7b7d'}" :data="tableData" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号" align="center" />
        <el-table-column prop="sysOrderId" label="订单ID" align="center">
          <template v-slot="scope">
            <el-link type="primary" @click="lookDetail(scope.row)">{{ scope.row.sysOrderId || '' }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" label="商品名称" align="center">
          <template v-slot="scope">
            {{ scope.row.goodsName || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="shopName" label="品类" align="center" min-width="200">
          <template v-slot="scope">
            <span>{{ scope.row.brandName }}</span>
            <span v-show="scope.row.categoryName">【{{ scope.row.categoryName }}】</span>
          </template>
        </el-table-column>
        <el-table-column prop="channelName" label="上游平台" align="center">
          <template v-slot="scope">
            {{ scope.row.channelName || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="officialPrice" label="官方价(元)" align="center" min-width="100">
          <template v-slot="scope">
            {{ numFormat(scope.row.officialPrice) || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="costPrice" label="成本(元)" align="center" min-width="100">
          <template v-slot="scope">
            {{ numFormat(scope.row.costPrice) || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="salePrice" label="售价(元)" align="center" min-width="100">
          <template v-slot="scope">
            {{ numFormat(scope.row.salePrice) || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="goodsNum" label="数量" align="center">
          <template v-slot="scope">
            {{ scope.row.goodsNum || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="payMoney" label="支付金额(元)" align="center" min-width="110">
          <template v-slot="scope">
            {{ numFormat(scope.row.payMoney) || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="shopName" label="商户" align="center">
          <template v-slot="scope">
            {{ scope.row.shopName || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="buyUserName" label="用户" align="center">
          <template v-slot="scope">
            {{ scope.row.buyUserName || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="状态" align="center" width="100">
          <template v-slot="scope">
            <span :class="'state'+scope.row.orderStatus"></span>
            {{ getStatus(scope.row.orderStatus) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" align="center" width="170">
          <template v-slot="scope">
            {{ scope.row.createTime ? getDateTime(scope.row.createTime)[6] : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="operations" label="操作" align="center" width="100" fixed="right">
          <template v-slot="scope">
            <el-link v-show="scope.row.orderStatus == 5 || scope.row.orderStatus == 8" style="font-size:14px;" type="danger"
              @click="handleClick(scope.row)">核减</el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-footer">
        <div>
          <el-button :disabled="chooseList.length == 0" plain @click="exportHandle(2)">批量导出</el-button>
        </div>
        <el-pagination v-model:currentPage="page" v-model:page-size="size" :page-sizes="[10, 20, 50, 100]" small
          :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
  <subtraction ref="subtractionRef" @dialogClose="subDialogClose" />
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
import api from '../api'
import { numFormat, getDateTime, getWindowWidthAndHeight, warningDeal, BlobDownLoad } from '@/utils/utils'
import { useRouter } from 'vue-router'
import subtraction from '@/components/subtraction.vue'
export default {
  components: {
    subtraction
  },
  setup() {
    const router = useRouter()

    const subtractionRef = ref(null)

    const state = reactive({
      typeId: null,
      page: 1,
      size: 10,
      total: 0,
      tableHeight: 0,
      searchForm: {},
      tableData: [],
      chooseList: [],
      goodsOptions: [],
      shopOptions: [],
      statusOptions: [
        {
          value: 1,
          label: '待支付',
        },
        {
          value: 2,
          label: '已支付',
        },
        {
          value: 3,
          label: '已受理',
        },
        {
          value: 4,
          label: '部分成功-进行中',
        },
        {
          value: 5,
          label: '成功',
        },
        {
          value: 6,
          label: '关闭',
        },
        {
          value: 7,
          label: '失败',
        },
        {
          value: 8,
          label: '部分成功-已完成',
        },
      ],
      channelOptions: [],
    })

    function getChannelOptions() {
      api.channelList().then(res => {
        if (res.code == '200') {
          state.channelOptions = res.data.list
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    async function getGoodsType() {
      await api.goodsTypeSimple().then(res => {
        if (res.code == '200') {
          state.typeId = (() => {
            let typeId = null
            res.data.map(item => {
              if (item.typeName.indexOf('卡券') > -1) {
                typeId = item.typeId
              }
            })
            return typeId
          })()
        } else {
          console.log(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function getStatus(value) {
      let label = ''
      state.statusOptions.map(item => {
        if (item.value == value) {
          label = item.label
        }
      })

      return label
    }

    function getShopAll() {
      api.shopListAll().then(res => {
        if (res.code == '200') {
          state.shopOptions = res.data
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function getGoodsAll() {
      api.goodsInfoAll().then(res => {
        if (res.code == '200') {
          state.goodsOptions = res.data
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function getOrderIds() {
      const myArr = []
      state.chooseList.map(item => {
        item.sysOrderId && myArr.push(item.sysOrderId)
      })
      return myArr
    }

    function exportHandle(i) {
      let obj = {
        responseType: "blob",
        submitType: 1,
        typeId: state.typeId,
        ...state.searchForm,
        createTimeStart: (state.searchForm.date && state.searchForm.date.length > 0) ? state.searchForm.date[0].getTime() : null,
        createTimeEnd: (state.searchForm.date && state.searchForm.date.length > 0) ? state.searchForm.date[1].getTime() : null,
      }
      if (i == 2) {
        obj = {
          responseType: "blob",
          sysOrderId: getOrderIds().join(','),
        }
      }
      api.manageOrderDown(obj).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
      })
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        submitType: 1,
        orderBy: 'id desc',
        typeId: state.typeId,
        ...state.searchForm,
        createTimeStart: (state.searchForm.date && state.searchForm.date.length > 0) ? state.searchForm.date[0].getTime() : null,
        createTimeEnd: (state.searchForm.date && state.searchForm.date.length > 0) ? state.searchForm.date[1].getTime() : null,
      }
      api.manageOrderList(obj).then(res => {
        if (res.code == '200') {
          state.tableData = res.data.list
          state.total = res.data.total
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.searchForm = {}
      searchHandle()
    }

    function handleSelectionChange(e) {
      state.chooseList = e
    }

    function lookDetail(data) {
      router.push({ path: '/dlOrder/detail', query: { sysOrderId: data.sysOrderId } })
    }


    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function subDialogClose() {
      getTableData()
    }

    function handleClick(data) {
      subtractionRef.value.dialogShow(data.sysOrderId)
    }

    onMounted(async () => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 360
      await getGoodsType()
      getGoodsAll()
      getShopAll()
      getTableData()
      getChannelOptions()
    })

    return {
      ...toRefs(state),
      subtractionRef,
      exportHandle,
      searchHandle,
      resetHandle,
      handleSelectionChange,
      numFormat,
      getDateTime,
      getStatus,
      lookDetail,
      handleSizeChange,
      handleCurrentChange,
      subDialogClose,
      handleClick,
    }
  }
}
</script>

<style lang="scss" scoped>
.coupon-box {
  width: 100%;
  height: 100%;
  .title-box {
    display: flex;
    align-items: center;
    > span {
      font-size: 14px;
      font-weight: bold;
    }
  }
  .search-box {
    display: flex;
    align-items: center;
    gap: 20px;
    box-sizing: border-box;
    padding: 5px;
    margin-top: 10px;
    > div {
      display: flex;
      width: 25%;
      align-items: center;
      > span {
        flex-shrink: 0;
        font-size: 14px;
      }
    }
  }
}
.table-box {
  margin-top: 10px;
  .table-footer {
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>